import { Controller, Post, Get, Body, UnauthorizedException, HttpCode, HttpStatus, Param, Query, ParseIntPipe,UseGuards } from '@nestjs/common';

import { JourneyService } from './journey.service';
import { Journey } from './schemas/journey.schema';
import { AuthGuard } from '@nestjs/passport';

import { Public } from "@src/login/decorators/public.decorator"
import { JwtAuthGuard}  from "../auth/jwt-auth.guard"
import { RolesGuard } from "../auth/roles.guard"

import * as dotenv from 'dotenv'; // 导入 dotenv
const dotenvInstance = dotenv.config();

const maxPublishJourney : string | number = dotenvInstance.parsed.MAX_PUBLISH_JOURNEY || 20 // 每个人每天最多能发布的条数

@Controller('/v1/api/journey')
export class JourneyController {
    constructor(private readonly journeyService: JourneyService) {}

    @UseGuards(AuthGuard('jwt'))
    @Public()
    @HttpCode(HttpStatus.OK)
    @Post('create')
    async createJourney( @Body() journeyInfo: Journey) {
    const journeysToday = await this.journeyService.countJoruneysToday(journeyInfo.publisher_id);
    if (journeysToday > Number(maxPublishJourney)) { // 每个用户每天只能发布20条行程
        throw new UnauthorizedException('每个用户每天只能发布20条行程');
    }

      const joruney = await this.journeyService.createJourney(journeyInfo);
      if (!joruney) {
        throw new UnauthorizedException();
      }
    //   return joruney;
        return {
            code: 200,
            message: '行程发布成功',
            data: joruney
        }
    }

    @UseGuards(AuthGuard('jwt'))
    @Public()
    @HttpCode(HttpStatus.OK)
    @Get('page')
    async getJoruneysByPage(
        @Query('page', ParseIntPipe) page: number,
        @Query('limit', ParseIntPipe) limit: number,
        @Query('departure') departure: string,
        @Query('destination') destination: string,
        @Query('date') date: string,
        @Query('sort') sort: string,
        @Query('price') price: string,
        @Query('keyword') keyword: string
        ) {
            const joruneys = await this.journeyService.getJoruneysByPage({page, limit, departure, destination, date, sort, price, keyword});
            return {data:{data: joruneys.data, total: joruneys.total}, code: 200, message: '获取行程成功'};
    }


    // @UseGuards(AuthGuard('jwt'), RolesGuard)
    @UseGuards(AuthGuard('jwt'))
    @Public()
    @HttpCode(HttpStatus.OK)
    @Get('joruneyDetail/:id')
    async getJoruneyById(@Param('id') id: string) {
      const joruney = await this.journeyService.findJoruneyById(id);
      if (!joruney) {
        throw new UnauthorizedException();
      }
      return joruney;
    }

   

}
